<?php
/**
 *
 * User: 梁晓伟  lxw11109@gmail.com
 * Date: 2017-11-05
 * Time: 16:37
 */

namespace App\Http\Controllers\Api\V1\Manager\Good;


use App\Exports\UniversalExport;
use App\Http\Controllers\Controller;
use App\Libs\httpUtil;
use App\Models\Banner;
use App\Models\Brand;
use App\Models\Expressfee;
use App\Models\Good;
use App\Models\GoodsOneType;
use App\Models\GoodsSpecOne;
use App\Models\GoodsSpecTwo;
use App\Models\GoodsStock;
use App\Models\GoodsTwoType;
use App\Models\GoodsWelfare;
use App\Models\Order;
use App\Models\OrderDetail;
use App\Models\Supplier;
use App\Models\UserHome;
use App\Models\UserStatistics;
use App\Models\VipLog;
use App\Services\Manager\GoodsService;
use DateTime;
use Illuminate\Http\Request;
use Maatwebsite\Excel\Facades\Excel;

class GoodWelfareController extends Controller
{

    private $namespace = "App\Http\Controllers\Api\V1\Manager\Good\GoodWelfareController";

    public function index(Request $request)
    {
        $goods_id = $request->goods_id;
        $welfare_status = $request->welfare_status;
        $nickname = $request->nickname;
        $phone = $request->phone;
        $ids = $request->ids;
        $idList = [];
        if (isset($ids)) {
            $ids = explode(';', $ids);
            foreach ($ids as $v) {
                $idList[] = $v;
            }
        }
        $pageSize = $request->pageSize;
        $sql = GoodsWelfare::select('t1.id', 't2.name as goods_name', 't1.goods_stock_id', 't3.image as goods_stock_image', 't4.name as goods_stock_name', 't4.name as goods_spec_one_name', 't5.name as goods_spec_two_name', 't3.cost_price', 't3.pure_cost_price',
            't1.welfare_price', 't6.nickname', 't6.phone', 't1.welfare_status', 't1.create_time', 't1.use_time',
            't1.goods_name as b_goods_name', 't1.goods_stock_image as b_goods_stock_image', 't1.goods_stock_name as b_goods_stock_name', 't1.cost_price as b_cost_price', 't1.pure_cost_price as b_pure_cost_price', 't1.url')
            ->from((new GoodsWelfare())->getTable() . ' as t1')
            ->leftJoin((new Good())->getTable() . ' as t2', 't1.goods_id', '=', 't2.id')
            ->leftJoin((new GoodsStock())->getTable() . ' as t3', 't1.goods_stock_id', '=', 't3.id')
            ->leftJoin((new GoodsSpecOne())->getTable() . ' as t4', 't3.goods_spec_one_id', '=', 't4.id')
            ->leftJoin((new GoodsSpecTwo())->getTable() . ' as t5', 't3.goods_spec_two_id', '=', 't5.id')
            ->leftJoin((new UserHome())->getTable() . ' as t6', 't1.user_id', '=', 't6.id')
            ->where('t1.goods_id', $goods_id);
        if (isset($idList[0])) {
            $sql->whereIn('t1.id', $idList);
        }
        if (isset($nickname)) {
            $sql->where('t6.nickname', 'like', "%$nickname%");
        }
        if (isset($phone)) {
            $sql->where('t6.phone', 'like', "%$phone%");
        }
        if (isset($welfare_status)) {
            $sql->where('t1.welfare_status', $welfare_status);
        }
        if (isset($request->excel)) {
            $welfareList = $sql->orderByDesc('t1.create_time')
                ->get()
                ->toArray();
            foreach ($welfareList as $key => $value) {
                $welfareList[$key]['goods_stock_name'] = $value['goods_spec_one_name'] . "/" . $value['goods_spec_two_name'];
                if ($value['welfare_status'] == 1) {
                    $welfareList[$key]['goods_name'] = $value['b_goods_name'];
                    $welfareList[$key]['goods_stock_image'] = $value['b_goods_stock_image'];
                    $welfareList[$key]['goods_stock_name'] = $value['b_goods_stock_name'];
                    $welfareList[$key]['cost_price'] = $value['b_cost_price'];
                    $welfareList[$key]['pure_cost_price'] = $value['b_pure_cost_price'];
                }
            }
            $title = ['福利id', '链接地址', '商品名称', '商品规格名称', '商品成本价', '商品不含税成本价', '福利价格', '领取人昵称', '领取人电话', '福利状态', '创建时间', '使用时间'];
            $data = [];
            $status = [0 => '未使用', 1 => '已使用', 2 => '已废弃', 3 => '已过期'];
            foreach ($welfareList as $value) {
                $welfare = [];
                $welfare[] = $value['id'];
                $welfare[] = $value['url'];
                $welfare[] = $value['goods_name'];
                $welfare[] = $value['goods_stock_name'];
                $welfare[] = $value['cost_price'];
                $welfare[] = $value['pure_cost_price'];
                $welfare[] = $value['welfare_price'];
                $welfare[] = $value['nickname'];
                $welfare[] = $value['phone'];
                $welfare[] = $status[$value['welfare_status']];
                $welfare[] = $value['create_time'];
                $welfare[] = $value['use_time'];
                $data[] = $welfare;
            }
            return Excel::download(new UniversalExport($data, $title), "商品福利状况" . date("ymdHis") . '.xlsx');
        }
        $welfareList = $sql->orderByDesc('t1.create_time')
            ->paginate($pageSize)
            ->toArray();
        $data['welfareList'] = $welfareList['data'];
        foreach ($data['welfareList'] as $key => $value) {
            $data['welfareList'][$key]['goods_stock_name'] = $value['goods_spec_one_name'] . "/" . $value['goods_spec_two_name'];
            if ($value['welfare_status'] == 1) {
                $data['welfareList'][$key]['goods_name'] = $value['b_goods_name'];
                $data['welfareList'][$key]['goods_stock_image'] = $value['b_goods_stock_image'];
                $data['welfareList'][$key]['goods_stock_name'] = $value['b_goods_stock_name'];
                $data['welfareList'][$key]['cost_price'] = $value['b_cost_price'];
                $data['welfareList'][$key]['pure_cost_price'] = $value['b_pure_cost_price'];
            }
            unset($data['welfareList'][$key]['goods_spec_one_name']);
            unset($data['welfareList'][$key]['goods_spec_two_name']);
            unset($data['welfareList'][$key]['b_goods_name']);
            unset($data['welfareList'][$key]['b_goods_stock_image']);
            unset($data['welfareList'][$key]['b_goods_stock_name']);
            unset($data['welfareList'][$key]['b_cost_price']);
            unset($data['welfareList'][$key]['b_pure_cost_price']);
        }
        $data['totalNum'] = $welfareList['total'];
        return $this->apiResponse($data);
    }

    public function show(Request $request, $id)
    {
        $welfare = GoodsWelfare::select('t1.id', 't2.name as goods_name', 't1.goods_stock_id', 't3.image as goods_stock_image', 't4.name as goods_stock_name', 't4.name as goods_spec_one_name', 't5.name as goods_spec_two_name', 't3.cost_price', 't3.pure_cost_price',
            't1.welfare_price', 't6.nickname', 't6.phone', 't1.welfare_status', 't1.create_time', 't1.use_time',
            't1.goods_name as b_goods_name', 't1.goods_stock_image as b_goods_stock_image', 't1.goods_stock_name as b_goods_stock_name', 't1.cost_price as b_cost_price', 't1.pure_cost_price as b_pure_cost_price', 't1.url')
            ->from((new GoodsWelfare())->getTable() . ' as t1')
            ->leftJoin((new Good())->getTable() . ' as t2', 't1.goods_id', '=', 't2.id')
            ->leftJoin((new GoodsStock())->getTable() . ' as t3', 't1.goods_stock_id', '=', 't3.id')
            ->leftJoin((new GoodsSpecOne())->getTable() . ' as t4', 't3.goods_spec_one_id', '=', 't4.id')
            ->leftJoin((new GoodsSpecTwo())->getTable() . ' as t5', 't3.goods_spec_two_id', '=', 't5.id')
            ->leftJoin((new UserHome())->getTable() . ' as t6', 't1.user_id', '=', 't6.id')
            ->where('t1.id', $id)
            ->first();
        $welfare['goods_stock_name'] = $welfare['goods_spec_one_name'] . "/" . $welfare['goods_spec_two_name'];
        if ($welfare['welfare_status'] == 1) {
            $welfare['goods_name'] = $welfare['b_goods_name'];
            $welfare['goods_stock_image'] = $welfare['b_goods_stock_image'];
            $welfare['goods_stock_name'] = $welfare['b_goods_stock_name'];
            $welfare['cost_price'] = $welfare['b_cost_price'];
            $welfare['pure_cost_price'] = $welfare['b_pure_cost_price'];
        }
        unset($welfare['goods_spec_one_name']);
        unset($welfare['goods_spec_two_name']);
        unset($welfare['b_goods_name']);
        unset($welfare['b_goods_stock_image']);
        unset($welfare['b_goods_stock_name']);
        unset($welfare['b_cost_price']);
        unset($welfare['b_pure_cost_price']);
        return $this->apiResponse($welfare);
    }

    public function store(Request $request)
    {
        $id = $request->id;
        $data = $request->only('goods_stock_id', 'welfare_price');
        $goodstock = GoodsStock::where('id', $data['goods_stock_id'])->first();
        if (!$goodstock || !$data['welfare_price'] || $data['welfare_price'] <= 0) {
            return $this->apiResponse('', config('errorLiu.NOTCANSHUID'));
        }
        $data['goods_id'] = $goodstock['goods_id'];
        try {
            \DB::beginTransaction();
            if ($id) {
                //修改
                $content = "修改";
                GoodsWelfare::where('id', $id)->where('welfare_status', 0)->update($data);
            } else {
                //新增
                $content = "新增";
                $data['create_time'] = date("Y-m-d H:i:s");
                $id = GoodsWelfare::insertGetId($data);
                $token = new \App\Services\Front\WxService();
                $access_token = $token->getAccessToken();
                $url = "https://api.weixin.qq.com/wxa/generatescheme?access_token=$access_token";
                $body = [
                    'jump_wxa' => (object)[
                        'path' => "pages/home/activityDetail/activityDetail",
                        'query' => "id=$id"
                    ],
                    'expire_type' => 1,
                    'expire_interval' => 30
                ];
                $http = new httpUtil();
                $res = $http->request($url, $body);
                if ($res['errcode']) {
                    return $this->apiResponse('', config('errorLiu.SHENGCHENGWAILOAINSHNIB'));
                }
                $url = $res['openlink'];
                GoodsWelfare::where('id', $id)->update(['url' => $url]);
            }
            $num = GoodsWelfare::where('goods_id', $data['goods_id'])->where('welfare_status', 0)->count();
            if ($num) {
                Good::where('id', $data['goods_id'])->update(['is_welfare' => 1]);
            } else {
                Good::where('id', $data['goods_id'])->update(['is_welfare' => 0]);
            }
            //添加管理员日志开始
            $url = $this->namespace . "/store";
            $title = $content;
            $content .= "了id为【" . $id . "】的商品福利,内容为【" . json_encode($data) . "】";
            $this->addAdminLog($request->ADMINID, $request->ADMINUSERNAME, $url, "商品福利模块", $title, $content, $request->getClientIp());
            //添加管理员日志结束
            \DB::commit();
            return $this->apiResponse(true);
        } catch (\Exception $e) {
            \DB::rollback();
            return $this->apiResponse('', config('errorCode.INVALID_REQ_PARAMS'));
        }
    }
}